<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="平台名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入平台名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <div class="table-header">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%"
        :height="tableHeight"
      >
        <el-table-column label="平台名称" prop="name" align="center" />
        <el-table-column label="客服电话" prop="phoneNo" align="center" />
        <el-table-column label="电话服务时间" prop="serviceTime" align="center" />
        <el-table-column label="所需资料内容" prop="requiredInfo" align="center" />
        <el-table-column label="缓催政策" prop="delayPolicy" align="center" />
        <el-table-column label="特殊网贷方案" prop="specialLoanPlan" align="center" />
        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template #default="{ row }">
            <el-button type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'edit' ? '编辑' : '新增'"
      width="50%"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="平台名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入标签名" />
        </el-form-item>
        <el-form-item label="客户电话" prop="phoneNo">
          <el-input v-model="formData.phoneNo" placeholder="请输入值" />
        </el-form-item>
        <el-form-item label="电话服务时间" prop="serviceTime">
          <el-input v-model="formData.serviceTime" placeholder="请输入电话服务时间" />
        </el-form-item>
        <el-form-item label="所需资料内容" prop="requiredInfo">
          <el-input v-model="formData.requiredInfo" placeholder="请输入所需资料内容" />
        </el-form-item>
        <el-form-item label="缓催政策" prop="delayPolicy">
          <el-input v-model="formData.delayPolicy" placeholder="请输入缓催政策" />
        </el-form-item>
        <el-form-item label="特殊网贷方案" prop="specialLoanPlan">
          <el-input v-model="formData.specialLoanPlan" placeholder="请输入特殊网贷方案" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/config/axios'

const list = ref([])
const listLoading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('new')
const formRef = ref()
const total = ref(0)
const tableHeight = ref(0)
const queryParams = ref({
  name: '',
  current: 1,
  size: 10
})

// 计算表格高度
const calculateTableHeight = () => {
  const windowHeight = window.innerHeight
  const otherHeight = 300 // 其他元素的高度（查询条件、按钮、分页等）
  tableHeight.value = windowHeight - otherHeight
}

// 监听窗口大小变化
const handleResize = () => {
  calculateTableHeight()
}

onMounted(() => {
  calculateTableHeight()
  window.addEventListener('resize', handleResize)
  getList()
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

const formData = ref({
  label: '',
  value: '',
  serviceTime: '',
  requiredInfo: '',
  delayPolicy: '',
  specialLoanPlan: ''
})

const formRules = {
  name: [
    { required: true, message: '请输入标签名', trigger: 'blur' }
  ],
  phoneNo: [
    { required: true, message: '请输入值', trigger: 'blur' }
  ],
  // serviceTime: [
  //   { required: true, message: '请输入电话服务时间', trigger: 'blur' }
  // ],
  requiredInfo: [
    { required: true, message: '请输入所需资料内容', trigger: 'blur' }
  ],
  delayPolicy: [
    { required: true, message: '请输入缓催政策', trigger: 'blur' }
  ],
  // specialLoanPlan: [
  //   { required: true, message: '请输入特殊网贷方案', trigger: 'blur' }
  // ]
}

// 查询
const handleQuery = () => {
  queryParams.value.current = 1
  getList()
}

// 每页条数改变
const handleSizeChange = (val) => {
  queryParams.value.size = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.current = val
  getList()
}

// 获取列表数据
const getList = async () => {
  listLoading.value = true
  try {
    const res = await request.get({ 
      url: '/kfPhone/list',
      params: queryParams.value
    })
    list.value = res.records || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    listLoading.value = false
  }
}

// 新增
const handleAdd = () => {
  dialogType.value = 'new'
  formData.value = {
    label: '',
    value: '',
    serviceTime: '',
    requiredInfo: '',
    delayPolicy: '',
    specialLoanPlan: ''
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.delete({ url: '/kfPhone/delete', params: {id: row.id} })
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 确认提交
const confirm = async () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (dialogType.value === 'new') {
        await request.post({ url: '/kfPhone/add', data: formData.value })
        ElMessage.success('新增成功')
      } else {
        await request.post({ url: '/kfPhone/update', data: formData.value })
        ElMessage.success('更新成功')
      }
      
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error('操作失败:', error)
    }
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
}
.filter-container {
  margin-bottom: 20px;
}
.demo-form-inline {
  display: inline-block;
  margin-right: 20px;
}
.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  height: calc(100% - 100px);
  display: flex;
  flex-direction: column;
}
.table-header {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
